package com.nf.controller.home;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.nf.config.AlipayConfig;
import com.nf.controller.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/api/AlipayServlet.do")
public class AlipayServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id= Integer.parseInt(req.getParameter("orderId"));
        Float price= Float.valueOf(req.getParameter("price"));
        String orderName=req.getParameter("orderName");


        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);


        alipayRequest.setBizContent("{\"out_trade_no\":\""+ id +"\","
                + "\"total_amount\":\""+ price +"\","
                + "\"subject\":\""+ orderName +"\","
                + "\"body\":\""+ "笑傲江湖影院票单" +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = null;
        try {
            resp.setContentType("text/html;charset=utf-8");
            result = alipayClient.pageExecute(alipayRequest).getBody();
            //输出
            PrintWriter out = resp.getWriter();
            out.println(result);

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }
}
